<script setup>
import { nextTick, onMounted, ref, shallowRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import VUpload from '@/components/upload/index.vue'
import Tabs from '@/components/tabs/index.vue'
import DangerNoticeForm from './components/DangerNoticeForm.vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {
  addSpecial,
  getSpecialDetail,
  updateSpecial,
} from '@/api/manager/inspectionManage/specialManage.js'
import { tenantPageList } from '@/api/manager/dataManage/tenant'
import {
  getDepartmentList,
  getUserByChoose,
} from '@/api/manager/systemManage/user.js'
import { getDangerList } from '@/api/manager/inspectionManage/rectificationManage.js'
import { useDict } from '@/hooks/useDict'

const router = useRouter()
const route = useRoute()

const { dict, getDictValue } = useDict([
  'special_task_type',
  'special_task_publish_scope',
  'video_watch_duration_unit',
  'yn',
  'rectification_notice_template',
])

const dangerNoticeFormRef = ref()
const formRef = ref()

const form = ref({
  learnDuration: 5,
  durationUnit: '1',
  needFeedBack: '0',
  attachmentFiles: [],
  noticeFiles: [],
  coverImages: [],
  attachmentVideos: [],
  userIds: [],
  receiveUnitIds: [],
})
const rules = ref({
  name: [
    {
      message: '请输入任务名称',
      required: true,
      trigger: 'blur',
    },
  ],
  needFeedBack: [
    {
      message: '请选择是否必须回传图片',
      required: true,
      trigger: 'blur',
    },
  ],
  taskType: [
    {
      message: '请选择任务类型',
      required: true,
      trigger: 'blur',
    },
  ],
  receiveUnitIds: [
    {
      message: '请选择接收单位',
      required: true,
      trigger: 'blur',
    },
  ],
  userIds: [
    {
      message: '请选择接受人',
      required: true,
      trigger: 'blur',
    },
  ],
  publishScope: [
    {
      message: '请选择发布范围',
      required: true,
      trigger: 'blur',
    },
  ],
  noticeTitle: [
    {
      message: '请输入公告标题',
      required: true,
      trigger: 'blur',
    },
  ],
  // userIds: [
  //   {
  //     message: '请选择接收人',
  //     required: true,
  //     trigger: 'blur',
  //   },
  // ],
  startDate: [
    {
      message: '请选择有效期',
      required: true,
      trigger: 'blur',
    },
  ],
  learnDuration: [
    {
      message: '请选择最小观看时间',
      required: true,
      trigger: 'blur',
    },
  ],
  durationUnit: [
    {
      message: '请选择时间单位',
      required: true,
      trigger: 'blur',
    },
  ],
  coverImages: [
    {
      message: '请选择封面图片',
      required: true,
      trigger: 'blur',
    },
  ],
  templeteType: [
    {
      message: '请选择通知公告模版',
      required: true,
      trigger: 'blur',
    },
  ],
  attachmentVideos: [
    {
      message: '请上传观看视频',
      required: true,
      trigger: 'blur',
    },
  ],
  noticeFiles: [
    {
      message: '请上传公告文件',
      required: true,
      trigger: 'blur',
    },
  ],
})
const disabledDate = (time) => {
  const nowTime = Date.now() - 8.64e7
  if (form.value.startDate) {
    const beginTime = new Date(form.value.startDate) - 8.64e7
    if (beginTime > nowTime) {
      return time.getTime() < beginTime
    } else {
      return time.getTime() < nowTime
    }
  } else {
    return time.getTime() < nowTime
  }
}

const tabsConfig = ref([])
const currentComponentKey = ref('')
const handleChangeTab = (val) => {
  currentComponentKey.value = val
}

// 富文本编辑器
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const toolbarConfig = {}
//富文本
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {},
}
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 修改任务类型
// 重置任务说明、附件、视频、模版内容
// 修改tab显示
const handleChangeTaskType = (isReset = true) => {
  if (form.value.taskType === '1') {
    tabsConfig.value = [
      {
        name: '任务内容',
        value: 'taskContent',
      },
      {
        name: '通知模版',
        value: 'noticeModel',
      },
    ]
  } else if (form.value.taskType === '2') {
    tabsConfig.value = [
      {
        name: '任务内容',
        value: 'taskContent',
      },
    ]
  }
  currentComponentKey.value = 'taskContent'

  if (isReset) {
    form.value.attachmentFiles = []
    form.value.noticeFiles = []
    form.value.attachmentVideos = []
    form.value.templeteType = ''
    form.value.content = ''
  }
}
const handleChangePublishScope = () => {
  form.value.receiveUnitIds = []
  form.value.userIds = []
  chooseUnitName.value = ''
  chooseUserName.value = ''
}

const tenantOptions = ref([])
const initTenantOptions = async () => {
  const res = await tenantPageList({ pageIndex: 1, pageSize: 9999 })
  tenantOptions.value = res.data.list
}
const departmentOptions = ref([])
const initDepartmentOptions = async () => {
  const res = await getDepartmentList({ unitId: '10501' })
  if (!res.success) {
    ElMessage.error(res.message)
    return
  }
  departmentOptions.value = res.data
}
const chooseUnitName = ref('')
const chooseUserName = ref('')
const dangerContent = ref([])
const departmentPersonOptions = ref([])
const initDepartmentPersonOptions = async (isReset = true) => {
  if (form.value.receiveUnitIds.length === 0) {
    chooseUnitName.value = ''
    chooseUserName.value = ''
    form.value.userIds = []
    departmentPersonOptions.value = []
    return
  }
  const res = await getUserByChoose({
    deptId: form.value.receiveUnitIds,
    unitId: '10501',
    type: ['1'],
    userState: 1,
  })
  departmentPersonOptions.value = res.data

  if (isReset) {
    // 获取选中单位名称
    chooseUnitName.value = '资产分公司'
    // chooseUnitName.value = departmentOptions.value
    //   .filter((i) => form.value.receiveUnitIds.includes(i.pkid))
    //   .map((j) => {
    //     return j.name
    //   })
    //   .join(',')
    // 默认选中总经理
    form.value.userIds = res.data
      .filter((i) => i.mainPost === '总经理')
      .map((j) => {
        return j.pkid
      })
    handleChangeDepartmentPerson()
  }
}
const tenantPersonOptions = ref([])
const initTenantPersonOptions = async (isReset = true) => {
  if (form.value.receiveUnitIds.length === 0) {
    chooseUnitName.value = ''
    chooseUserName.value = ''
    form.value.userIds = []
    tenantPersonOptions.value = []
    return
  }
  const res = await getUserByChoose({
    unitContent: form.value.receiveUnitIds,
    type: ['2'],
    userState: 1,
  })
  tenantPersonOptions.value = res.data

  if (isReset) {
    // 获取选中单位名称
    chooseUnitName.value = tenantOptions.value
      .filter((i) => form.value.receiveUnitIds.includes(i.pkid))
      .map((j) => {
        return j.name
      })
      .join(',')

    // 默认选中主要负责人 mainPost = 1
    form.value.userIds = res.data
      .filter((i) => i.mainPost === '1')
      .map((j) => {
        return j.pkid
      })
    handleChangeTanantPerson()
  }
}
const handleChangeDepartmentPerson = () => {
  chooseUserName.value = departmentPersonOptions.value
    .filter((i) => form.value.userIds.includes(i.pkid))
    .map((j) => {
      return j.userName
    })
    .join(',')
}
const handleChangeTanantPerson = () => {
  chooseUserName.value = tenantPersonOptions.value
    .filter((i) => form.value.userIds.includes(i.pkid))
    .map((j) => {
      return j.userName
    })
    .join(',')
}

const handleCancel = () => {
  router.push({ name: 'specialManage' })
}
const loading = ref(false)
const handleSubmit = (status) => {
  if (!formRef.value) return
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        const params = JSON.parse(JSON.stringify(form.value))
        params.taskStatus = status
        // 处理接收单位
        params.receiveUnitIds = params.receiveUnitIds.join(',')
        // 处理封面图片
        if (params.coverImages && params.coverImages.length > 0) {
          params.coverImageId = params.coverImages[0].pkid
        } else {
          params.coverImageId = ''
        }
        delete params.coverImages
        // 处理附件资料
        if (params.attachmentFiles && params.attachmentFiles.length > 0) {
          params.attachmentFileId = params.attachmentFiles
            .map((i) => i.pkid)
            .join(',')
        } else {
          params.attachmentFileId = ''
        }
        delete params.attachmentFiles
        // 处理公告文件
        if (params.noticeFiles && params.noticeFiles.length > 0) {
          params.noticeFileId = params.noticeFiles.map((i) => i.pkid).join(',')
        } else {
          params.noticeFileId = ''
        }
        delete params.noticeFiles
        // 处理视频
        if (params.attachmentVideos && params.attachmentVideos.length > 0) {
          params.attachmentVideoId = params.attachmentVideos[0].pkid
        } else {
          params.attachmentVideoId = ''
        }
        delete params.attachmentVideos
        // 处理模版
        if (params.taskType === '1') {
          params.templeteContent = JSON.stringify(
            dangerNoticeFormRef.value.form,
          )
        }
        let res
        loading.value = true
        try {
          if (!params.pkid) {
            res = await addSpecial(params)
          } else {
            res = await updateSpecial(params)
          }
          if (res.success) {
            ElMessage.success('保存成功')
            handleCancel()
          } else {
            ElMessage.error(res.message)
          }
          loading.value = false
        } catch (error) {
          loading.value = false
        }
      } catch (error) {
        console.log('error', error)
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}

const handleDetail = async () => {
  const res = await getSpecialDetail({ pkid: route.query.pkid })
  res.data.receiveUnitIds = res.data.receiveUnitIds.split(',')
  res.data.attachmentFiles = res.data.attachmentFiles
    ? res.data.attachmentFiles
    : []
  res.data.noticeFiles = res.data.noticeFiles ? res.data.noticeFiles : []
  res.data.attachmentVideos = res.data.attachmentVideos
    ? res.data.attachmentVideos
    : []
  res.data.coverImages = res.data.coverImages ? res.data.coverImages : []
  form.value = res.data
  handleChangeTaskType(false)
  if (form.value.publishScope === '1') {
    initDepartmentPersonOptions(false)
  } else {
    initTenantPersonOptions(false)
  }
}

const handleDangerDetail = async () => {
  const res = await getDangerList({
    pageIndex: 1,
    pageSize: 9999,
    dangerIds: route.query.dangerIds,
  })
  form.value.dangerIds = route.query.dangerIds
  form.value.taskType = '1'
  handleChangeTaskType(true)
  form.value.publishScope = res.data.list[0].repairCompany
  form.value.receiveUnitIds = [res.data.list[0].repairDept]
  form.value.userIds = [res.data.list[0].dutyPerson]
  if (form.value.publishScope === '1') {
    initDepartmentPersonOptions(false)
  } else {
    initTenantPersonOptions(false)
  }
  form.value.templeteType = '1'
  nextTick(() => {
    if (form.value.publishScope === '1') {
      chooseUnitName.value = '资产分公司'
    } else {
      chooseUnitName.value = res.data.list[0].repairDeptName
    }
    chooseUserName.value = res.data.list[0].dutyPersonName
    dangerContent.value = res.data.list.map((i) => {
      return i.repairDesc
    })
  })
}

onMounted(() => {
  initTenantOptions()
  initDepartmentOptions()
  // initDepartmentPersonOptions()
  // initTenantPersonOptions()
  if (route.query.pkid) {
    handleDetail()
  }
  if (route.query.dangerIds) {
    handleDangerDetail()
  }
})
</script>

<template>
  <div class="add-wrapper">
    <div class="top">
      <el-form ref="formRef" label-width="150" :model="form" :rules="rules">
        <div class="top-left">
          <el-form-item prop="name" label="任务名称：">
            <el-input v-model="form.name" clearable placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="taskType" label="任务类型：">
            <el-select
              v-model="form.taskType"
              placeholder="请选择"
              @change="handleChangeTaskType"
              :disabled="!!route.query.pkid || !!route.query.dangerIds"
            >
              <el-option
                v-for="option of dict['special_task_type']"
                :key="option.value"
                :label="option.name"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item
            prop="noticeTitle"
            label="公告标题："
            v-if="form.taskType === '3'"
          >
            <el-input
              v-model="form.noticeTitle"
              clearable
              placeholder="请输入"
            />
          </el-form-item> -->
          <el-form-item prop="publishScope" label="发布范围：">
            <el-select
              v-model="form.publishScope"
              placeholder="请选择"
              @change="handleChangePublishScope"
              :disabled="!!route.query.dangerIds"
            >
              <el-option
                v-for="option of dict['special_task_publish_scope']"
                :key="option.value"
                :label="option.name"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="receiveUnitIds"
            label="接收单位："
            v-if="form.publishScope === '1'"
          >
            <el-select
              v-model="form.receiveUnitIds"
              clearable
              multiple
              filterable
              placeholder="请选择"
              @change="initDepartmentPersonOptions"
              :disabled="!!route.query.dangerIds"
            >
              <el-option
                v-for="(item, index) of departmentOptions"
                :key="index"
                :label="item.name"
                :value="item.pkid"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="receiveUnitIds"
            label="接收单位："
            v-else-if="form.publishScope === '2'"
          >
            <el-select
              v-model="form.receiveUnitIds"
              clearable
              multiple
              filterable
              placeholder="请选择"
              @change="initTenantPersonOptions"
              :disabled="!!route.query.dangerIds"
            >
              <el-option
                v-for="(item, index) of tenantOptions"
                :key="index"
                :label="item.name"
                :value="item.pkid"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="userIds"
            label="接收人："
            v-if="form.publishScope === '1'"
          >
            <el-select
              v-model="form.userIds"
              clearable
              multiple
              filterable
              placeholder="请选择"
              @change="handleChangeDepartmentPerson"
              :disabled="!!route.query.dangerIds"
            >
              <el-option
                v-for="(item, index) of departmentPersonOptions"
                :key="index"
                :label="item.userName"
                :value="item.pkid"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="userIds"
            label="接收人："
            v-else-if="form.publishScope === '2'"
          >
            <el-select
              v-model="form.userIds"
              clearable
              multiple
              filterable
              placeholder="请选择"
              @change="handleChangeTanantPerson"
              :disabled="!!route.query.dangerIds"
            >
              <el-option
                v-for="(item, index) of tenantPersonOptions"
                :key="index"
                :label="item.userName"
                :value="item.pkid"
              />
            </el-select>
          </el-form-item>
          <el-row>
            <el-form-item prop="startDate" label="有效期：">
              <el-date-picker
                class="date-input1"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="form.startDate"
              />
            </el-form-item>
            <el-form-item class="no-ml" prop="endDate">
              <span class="separator">-</span>
              <el-date-picker
                :disabled="!form.startDate"
                class="date-input1"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="form.endDate"
                :disabled-date="disabledDate"
              />
              <span class="tips">为空则手动终止</span>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item prop="learnDuration" label="观看时限：">
              <span class="separator">设置最小观看时间为</span>
              <el-input
                class="watch-video-duration-input"
                v-model="form.learnDuration"
                type="number"
                :min="0"
              />
            </el-form-item>
            <el-form-item class="ml" prop="durationUnit">
              <el-select v-model="form.durationUnit" placeholder="请选择">
                <el-option
                  v-for="option of dict['video_watch_duration_unit']"
                  :key="option.value"
                  :label="option.name"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-row>
          <el-form-item prop="needFeedBack" label="是否必须回传图片：">
            <el-radio-group v-model="form.needFeedBack">
              <el-radio
                v-for="(item, index) of dict['yn']"
                :key="index"
                :value="item.value"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="feedBackDesc" label="回传图片说明：">
            <el-input
              v-model="form.feedBackDesc"
              clearable
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item prop="coverImages" label="封面图片：">
            <VUpload
              listType="picture-card"
              accept=".png, .jpg, .jepg"
              v-model="form.coverImages"
              :limit="1"
            />
          </el-form-item>
          <el-form-item
            prop="attachmentFiles"
            label="附件上传"
            v-if="form.taskType === '1'"
          >
            <VUpload
              v-model="form.attachmentFiles"
              accept=".pdf,.PDF,.xls,.xlsx,.doc,.docx,.png,.jpg,.jpeg"
            />
          </el-form-item>
          <el-form-item
            prop="noticeFiles"
            label="公告文件上传"
            v-if="form.taskType === '3'"
          >
            <VUpload v-model="form.noticeFiles" accept=".pdf,.PDF" :limit="1" />
          </el-form-item>
        </div>

        <div class="top-right" v-if="['1', '2'].includes(form.taskType)">
          <Tabs
            @change="handleChangeTab"
            :currentKey="currentComponentKey"
            :tabsConfig="tabsConfig"
          />
          <!-- 任务内容 -->
          <div
            class="top-right-task"
            v-show="currentComponentKey === 'taskContent'"
          >
            <el-form-item class="no-label-form-item" label="" prop="content">
              <div class="top-right-task-editor">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  mode="default"
                />
                <Editor
                  class="top-right-task-editor-main"
                  v-model="form.content"
                  :defaultConfig="editorConfig"
                  mode="default"
                  @onCreated="handleCreated"
                />
              </div>
            </el-form-item>
            <el-form-item
              v-if="form.taskType === '2'"
              class="small-form-item"
              prop="attachmentVideos"
              label="观看视频："
            >
              <VUpload
                v-model="form.attachmentVideos"
                :limit="1"
                :fileSize="200"
                accept=".mp4"
                tip="mp4格式，最大200M/个"
              />
            </el-form-item>
          </div>
          <!-- 通知模版 -->
          <div
            class="top-right-notice"
            v-show="currentComponentKey === 'noticeModel'"
          >
            <el-form-item
              class="small-form-item"
              prop="templeteType"
              label="请选择模版"
              v-if="currentComponentKey === 'noticeModel'"
            >
              <el-select
                v-model="form.templeteType"
                placeholder="请选择"
                class="date-input1"
              >
                <el-option
                  v-for="(item, index) of dict['rectification_notice_template']"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <div class="top-right-notice-form">
              <DangerNoticeForm
                ref="dangerNoticeFormRef"
                v-show="form.templeteType === '1'"
                :detail="form.templeteContent"
                :unitNames="chooseUnitName"
                :userNames="chooseUserName"
                :dangerList="dangerContent"
              />
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <div class="bottom">
      <el-button @click="handleCancel" :loading="loading">取消</el-button>
      <el-button
        v-if="!form.taskStatus || form.taskStatus === '-1'"
        @click="handleSubmit('-1')"
        :loading="loading"
        >保存</el-button
      >
      <el-button type="primary" @click="handleSubmit('0')" :loading="loading"
        >发布</el-button
      >
    </div>
  </div>
</template>

<style scoped lang="scss">
.add-wrapper {
  height: 100%;
  height: 100%;
  background: #ffffff;
  box-shadow: 0 0 10px 0 rgba(72, 121, 238, 0.1);

  .top {
    width: 100%;
    height: calc(100% - 70px);
    box-sizing: border-box;
    padding: 20px 20px 20px 20px;
    overflow-y: auto;
    .el-form {
      flex: 1;
      overflow-y: auto;
      display: flex;
      align-items: flex-start;
      justify-content: space-between;

      .tips {
        margin-left: 10px;
        color: #999999;
        font-size: 12px;
      }

      .separator {
        margin: 0 10px;
        color: #999999;
        font-size: 12px;
      }

      .el-form-item {
        &.no-ml {
          :deep(.el-form-item__content) {
            margin-left: 0 !important;
          }
        }

        &.ml {
          :deep(.el-form-item__content) {
            margin-left: 20px !important;

            .el-select {
              width: 100px;
            }
          }
        }
      }

      .el-form-item__content {
        & > div:not([class^='el-']) {
          width: 100%;
        }

        .watch-video-duration-input {
          width: 100px;
        }
      }

      :deep(.no-label-form-item) {
        .el-form-item__content {
          margin-left: 0px !important;
        }
      }
      :deep(.small-form-item) {
        .el-form-item__label {
          width: 100px !important;
        }
      }
    }
    :deep(.date-input1) {
      width: 190px;
      height: 100%;
    }
    &-left {
      width: 700px;
      height: 100%;
    }
    &-right {
      width: calc(100% - 720px);
      height: 100%;
      .tabs-wrapper {
        box-shadow: none;
        height: 30px;
      }
      &-task {
        width: calc(100% - 40px) !important;
        margin: 20px;
        &-editor {
          box-sizing: border-box;
          border-radius: 4px;
          border: 1px solid #d5deed;
          &-main {
            height: 500px !important;
            overflow-y: hidden;

            :deep(.w-e-text-placeholder) {
              top: 10px;
            }
          }
        }
      }
      &-notice {
        width: 100%;
        margin-top: 20px;
        &-form {
          width: 100%;
          overflow-y: auto;
          display: flex;
          align-items: flex-start;
          justify-content: center;
          box-sizing: border-box;
          padding: 20px 0;
        }
      }
    }
  }

  .bottom {
    width: 100%;
    height: 70px;
    box-sizing: border-box;
    border-top: 1px solid #d5deed;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
